/*
 * Detact Mobile Browser
 */
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
   $('html').addClass('ismobile');
}
User={},
User.loginInputValidation=function(){
	$('#responseText').html('');
	if(!$('#UserName').val() || $('#UserName').val().length < 1){
		User.showMessage('需要输入用户名且长度不小于5位！'); return false;
	}
	if(!$('#Password').val() || $('#Password').val().length < 6){
		User.showMessage('需要输入密码且长度不小于6位！'); return false;
	}
	if(document.getElementById("verifyCodeWrap").style.display != 'none'){
		if(!$('#VerifyCode').val() || $('#VerifyCode').val().length != 4){
			User.showMessage('需要输入验证码且长度为4位！'); return false;
		}
	}
	return true;
},
User.needVerifyCode = function(userName,callBack){//验证是否需要验证码，参数:用户名,回调函数
	if(User.showVerifyCode.showTimes[userName]){
		User.showVerifyCode(callBack);
		//callBack&&(typeof(callBack)=='function')&&callBack();
	}else if(userName.trim()!==''){
		var dc={UserName:userName};
		Server.sendRequest("Login.needVerifyCode",dc,function(response){
			if(response.Need){
				User.showVerifyCode(callBack);
			}else{
				$('#verifyCodeWrap').hide();
				callBack&&(typeof(callBack)=='function')&&callBack();
			}
		});
	}
},
User.showVerifyCode = function(callBack){
	$('#verifyCodeWrap').show();
	callBack&&(typeof(callBack)=='function')&&callBack();
	User.showVerifyCode.showTimes[$V('UserName')] = User.showVerifyCode.showTimes[$V('UserName')] ? User.showVerifyCode.showTimes[$V('UserName')] +1:1;
},
User.showVerifyCode.showTimes={},
User.byebyeIE6 = function(){
	if(isIE && ieVersion<8){
		var ie={
				'6':{
					y: new Date().getFullYear() - 2001
				},
				'7':{
					y: new Date().getFullYear() - 2006
				}
		}
		var msg;
		if(Lang.getCurrentLang()=='en'){
			msg='Find that you are using IE'+ieVersion+', the browser was released in '+ie[''+ieVersion].y+' years ago, the script execution is very low in it, We suggest you install a newer browsers to get the better operation experience.<br>'
			msg+='<br> download <a target="_blank" href="http://www.google.com.hk/chrome/">chrome</a>';
			msg+='&nbsp; download <a target="_blank" href="http://www.firefox.com.cn/download/">firefox</a>';
			msg+='&nbsp; download <a target="_blank" href="http://windows.microsoft.com/zh-cn/internet-explorer/downloads/ie-8/">IE8</a>';
			
		}else{
			msg='向您致以歉意：<br>　　发现您正在使用IE'+ieVersion+'浏览器，此浏览器已发布'+ie[''+ieVersion].y+'年，性能和兼容性较差，在此浏览器下本系统运行较慢。建议您安装最新的浏览器以获得流畅的使用体验。<br>';
			msg+='<br> 下载<a target="_blank" href="http://www.google.com.hk/chrome/">谷歌浏览器</a>';
			msg+='&nbsp; 下载<a target="_blank" href="http://www.firefox.com.cn/download/">火狐浏览器</a>';
			msg+='&nbsp; 下载<a target="_blank" href="http://windows.microsoft.com/zh-cn/internet-explorer/downloads/ie-8/">微软IE8</a>';
		}
		//mini.open({html:msg,width:500});
		top.mini.alert(msg);
		//$('#loginBar').html(msg);
		//$('#loginBar').css("padding-top","90px");
	}
	if(isIE && isLiebao){
		top.mini.alert('发现你正在使用猎豹浏览器的IE兼容模式，请在页面空白处点击右键并选择“切换到极速模式”，以获得更好的用户体验。');
	}
	if(is360Old){
		top.mini.alert('发现你正在使用低版本的360浏览器，请使用最新的360浏览器，以获得更好的用户体验。');
	}
},
User.onLanguageChange = function(obj){
	Server.sendRequest("Application.changeLanguage",{Language:obj.value},function(response){
		window.location.reload();
	});
},
User.onLoginClick = function() {
	if(!User.loginInputValidation()) return;
	var isVerifyCode = User.showVerifyCode.showTimes[$('#UserName').val()]?true:false;
	var data = {UserName:$('#UserName').val(),ClientType:"pc",Password:$('#Password').val(),Language:$('#LanguageSelector').val(), VerifyCode:$('#VerifyCode').val(),IsVerifyCode:isVerifyCode};
	Server.sendRequest("Login.submit",data,function(response){
		if(response&&response.Status==0){
			User.showVerifyCode();
			if(response.Focus){
				$("#"+response.Focus).focus();
			}
			User.showMessage(response.Message);
			$("#imgCode").click();
		}else if(response&&response.Status==408){
			User.showMessage('连接超时，可能的原因为网络中断或服务器错误，请稍后再试。');
		}else if(response&&response.Status==10000){
			swal({
				title:"",
                text: User.loginNotice,   
                type: "warning",   
                showCancelButton: true,
                cancelButtonText:User.cancelText,
                confirmButtonColor: "#0a6ebd",   
                confirmButtonText: User.okText,   
                closeOnConfirm: false 
            }, function(){   
            	data.IsVerifyCode = false;
				data.logout ="Y";
				Server.sendRequest("Login.submit",data,function(response){
					if(response&&response.Status==0){
						User.showMessage(response.Message);
						User.showVerifyCode();
					}else if(response&&response.Status==408){
						User.showMessage('连接超时，可能的原因为网络中断或服务器错误，请稍后再试。');
					}
				});
				$("#imgCode").click();
            });
		}
	});
},
User.showMessage=function(message){
	$('#login_error_container').html(message).addClass('animated bounceIn').show(); 
	setTimeout(function(){
		$('#login_error_container').removeClass('bounceIn');
    },800);
	setTimeout(function(){
		$('#login_error_container').html("").addClass('animated fadeOut').hide();
		setTimeout(function(){
			$('#login_error_container').removeClass('fadeOut');
	    },800);
    },5000);
},
User.preQrCode=function(){
    $('#login-module').toggleClass('login-module');
    //快速登陆模式
    if($('#login-module').hasClass('login-module')){
    	User.showQrCode();
    } 
    //密码登陆模式
    else {
    	clearInterval(User.qrCodeRefresher);
    }
},
//二维码计时器
User.qrCodeRefresher = {},
//刷新二维码
User.showQrCode=function(){
	$('#qrcode').attr('src', "login/safeqrcode?t=" + new Date().getTime());
	User.qrCodeRefresher = setInterval(function(){
		$('#qrcode').attr('src', "login/safeqrcode?t=" + new Date().getTime());
	}, 3*60*1000);
	
},
User.particlesDefault=function(){
	if ($('#pageIntroBgParticlesDefault')['length']) {
        particlesJS("pageIntroBgParticlesDefault", {
            "particles": {
                "number": {
                    "value": 30,
                    "density": {
                        "enable": true,
                        "value_area": 500
                    }
                },
                "color": {
                    "value": "#ffffff"
                },
                "opacity": {
                    "value": 1,
                    "random": false,
                    "anim": {
                        "enable": false,
                        "speed": 1,
                        "opacity_min": 0.1,
                        "sync": false
                    }
                },
                "size": {
                    "value": 4,
                    "random": true,
                    "anim": {
                        "enable": false,
                        "speed": 40,
                        "size_min": 0.1,
                        "sync": false
                    }
                },
                "line_linked": {
                    "enable": true,
                    "distance": 160,
                    "color": '#ffffff',
                    "opacity": 1,
                    "width": 1
                },
                "move": {
                    "enable": true,
                    "speed": 3,
                    "direction": "top-right",
                    "random": false,
                    "straight": false,
                    "out_mode": "out",
                    "bounce": false,
                    "attract": {
                        "enable": false,
                        "rotateX": 600,
                        "rotateY": 1200
                    }
                }
            },
            "interactivity": {
                "detect_on": "canvas",
                "events": {
                    "onhover": {
                        "enable": true,
                        "mode": "repulse"
                    },
                    "onclick": {
                        "enable": false,
                        "mode": "push"
                    },
                    "resize": true
                },
                "modes": {
                    "grab": {
                        "distance": 400,
                        "line_linked": {
                            "opacity": 1
                        }
                    },
                    "bubble": {
                        "distance": 400,
                        "size": 40,
                        "duration": 2,
                        "opacity": 8,
                        "speed": 3
                    },
                    "repulse": {
                        "distance": 200,
                        "duration": 0.4
                    },
                    "push": {
                        "particles_nb": 4
                    },
                    "remove": {
                        "particles_nb": 2
                    }
                }
            },
            "retina_detect": true
        });
        $('#pageIntroBgParticlesDefault canvas').css("height", "99%");
    } else {
        $('#pageIntroBgParticlesDefault').remove();
    }
}

$(document).on('keydown','input', function(evt){
	if(evt.keyCode==13){
		User.needVerifyCode($('#UserName').val(),User.onLoginClick);
		evt.preventDefault();
		evt.stopPropagation();
	}
});

$(document).ready(function(){
    /*
     * Clear Notification
     */
    $('body').on('click', '[data-clear="notification"]', function(e){
      e.preventDefault();
    
      var x = $(this).closest('.listview');
      var y = x.find('.lv-item');
      var z = y.size();
      
      $(this).parent().fadeOut();
      
      x.find('.list-group').prepend('<i class="grid-loading hide-it"></i>');
      x.find('.grid-loading').fadeIn(1500);
      
          
      var w = 0;
      y.each(function(){
          var z = $(this);
          setTimeout(function(){
          z.addClass('animated fadeOutRightBig').delay(1000).queue(function(){
              z.remove();
          });
          }, w+=150);
      })
	
	//Popup empty message
	setTimeout(function(){
	    $('#notifications').addClass('empty');
	}, (z*150)+200);
    });
    

    /*
     * Text Feild
     */
    //Add blue animated border and remove with condition when focus and blur
    if($('.fg-line')[0]) {
        $('body').on('focus', '.form-control', function(){
            $(this).closest('.fg-line').addClass('fg-toggled');
        })

        $('body').on('blur', '.form-control', function(){
            var p = $(this).closest('.form-group');
            var i = p.find('.form-control').val();
            
            if (p.hasClass('fg-float')) {
                if (i.length == 0) {
                    $(this).closest('.fg-line').removeClass('fg-toggled');
                }
            }
            else {
                $(this).closest('.fg-line').removeClass('fg-toggled');
            }
        });
    }
    
    //Add blue border for pre-valued fg-flot text feilds
    if($('.fg-float')[0]) {
        $('.fg-float .form-control').each(function(){
            var i = $(this).val();
            
            if (!i.length == 0) {
                $(this).closest('.fg-line').addClass('fg-toggled');
            }
            
        });
    }
    /*
     * Custom Select
     */
    if ($('.selectpickers')[0]) {
        $('.selecstpicker').selectpicker();
    }
    
    /*
     * Tag Select
     */
    if($('.tag-select')[0]) {
        $('.tag-select').chosen({
            width: '100%',
            allow_single_deselect: true
        });
    }
    
    /*
     * Input Mask
     */
    if ($('input-mask')[0]) {
        $('.input-mask').mask();
    }
    
    /*
     * Bootstrap Growl - Notifications popups
     */ 
    function notify(message, type){
        $.growl({
            message: message
        },{
            type: type,
            allow_dismiss: false,
            label: 'Cancel',
            className: 'btn-xs btn-inverse',
            placement: {
                from: 'top',
                align: 'right'
            },
            delay: 2500,
            animate: {
                    enter: 'animated bounceIn',
                    exit: 'animated bounceOut'
            },
            offset: {
                x: 20,
                y: 85
            }
        });
    };

    Waves.attach('.btn', ['waves-button', 'waves-float']);
    Waves.init();
    
    $("#UserName").select();
    
    if ($.support.cookies) {
        $('.login_inner_container').removeClass('no_display');
        $('.no_cookie').addClass('no_display');
      } else {
        $('.login_inner_container').addClass('no_display');
        $('.no_cookie').removeClass('no_display');
      }
  	if(Cookie.get('_lang')){
  		$('#LanguageSelector').val(Cookie.get('_lang'));
  	}
   	$('#UserName').change(function(){
   		var userName=this.value.trim();
   		if(userName == 'muya'){
   			$('body').css('-webkit-transform','rotate(180deg)');
   			$('body').css('-moz-transform','rotate(-180deg)');
   		} else {
   			$('body').css('-webkit-transform','rotate(0deg)');
   			$('body').css('-moz-transform','rotate(0deg)');
   		}
   		if(userName!==''){
   			User.needVerifyCode(userName);
   		}
   	});
  	$('#UserName').focus().select();
  	$('#UserName').closest('.fg-line').addClass('fg-toggled');
  	User.needVerifyCode($('#UserName').val());
  	User.byebyeIE6();
  	$('#login-toggle-module').on('click',function(){
  		User.preQrCode();
  	});
});
